#!/usr/bin/python3
# coding=utf8
import sys
sys.path.append('/home/pi/MasterPi/')
import paho.mqtt.client as mqtt
from controller import Controller,CMD_HEART_BIT
import threading
import time
import ctypes
import math
import json
import rtmp
import auth


class MqttClient:
    def __init__(self,ip,port,topic,controller):
        self.__topic=topic
        self.__ip=ip
        self.__port=port
        self.__controller = controller # 控制器对象
 
        self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,transport="websockets")
        self.client.on_connect = self.__on_connect
        self.client.on_message = self.__on_message
        self.client.on_connect_fail = self.__on_connect_fail
        self.client.username="admin"
        self.client.password="root1234!"
        mauth = auth.Auth()
        url = mauth.getPushUrl()
        #rtmp://101.132.123.218:1936/hls
        self.__rtmp = rtmp.CvRtmp(url)

    def publish(self,data):
        self.client.publish('topic/unmannedship/data',data,1)
    def sendGyroData(self,data):
        self.client.publish('topic/unmannedship/data/gyro',data,1)
        pass
    def sendGpsData(self,data):
        self.client.publish('topic/unmannedship/data/gps',data,1)
        pass
    def heatBeat(self):
        self.client.publish('topic/unmannedship/heartbeat',CMD_HEART_BIT,1)
    def sendVolt(self,data):
        self.client.publish('topic/unmannedship/data/volt',data,1)
    
    def stop(self):
        self.client.disconnect()

    def start(self):
        # 设置遗嘱消息，当树莓派断电，或者网络出现异常中断时，发送遗嘱消息给其他客户端
        self.client.will_set(self.__topic,  b'{"status": "Off"}')

        # 创建连接，三个参数分别为 broker 地址，broker 端口号，保活时间
        self.client.connect(self.__ip, self.__port, 60)

        # 设置网络循环堵塞，在调用 disconnect() 或程序崩溃前，不会主动结束程序
        self.client.loop_forever()

        self.client.disconnect()

    def __on_connect(self,client, userdata, flags, rc, other):
        print(f"Connected with result code {rc}")
        # 订阅，需要放在 on_connect 里
        # 如果与 broker 失去连接后重连，仍然会继续订阅 raspberry/topic 主题
        client.subscribe(self.__topic)
    
    def __on_connect_fail(self,client,userdata):
        print(f"Connected Failed!")
        self.__controller.emergencyStop()
 
    # 回调函数，当收到消息时，触发该函数
    def __on_message(self, client, userdata, msg):
        print(f"{msg.topic} {msg.payload}")
        jsonData = json.loads(msg.payload)
        cmd = jsonData['cmd']
        if(cmd==40):
            #open
            if not self.__rtmp.isRunning:
                print("开始运行ffmpeg")
                threading.Thread(target=self.__rtmp.start).start()
            else:
                print("已经运行ffmpeg")
        elif(cmd==41):
            #close
            print("关闭FFMPEG")
            self.__rtmp.isRunning = False
        else:
            self.__controller.exec(cmd,jsonData['data'])
    
 
    
 

if __name__ == '__main__':
    mq = MqttClient("101.132.123.218",11883,"topic/unmannedship/cmd")
    mq.start()
 
 